package com.yonyou.sto.modules.ums.util;

import com.yonyou.sto.modules.ims.service.impl.OpenBillServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;



public class HttpRestUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(OpenBillServiceImpl.class);
    /**
     * http post
     * */
    public static String post(String url, String params) throws IOException {
        return  send(url , params);
    }

    /**
     * http get
     * */
    public static String get(String url, String params) throws IOException {
        return  send(url, params);
    }

    /**
     * HttpMethod  post/get
     * */
    public static String send(String ip,String json) throws IOException {

        String urlNameString = ip;
        URL realUrl = new URL(urlNameString);
        InputStream inputStream = null;

        HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        connection.setRequestProperty("timestamp", System.currentTimeMillis()+"");
        connection.connect();

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
        writer.write(json);
        writer.close();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK ) {
            inputStream = connection.getErrorStream();
        }else{
            inputStream = connection.getInputStream();
        }
        LOGGER.debug("网络地址："+urlNameString+" ");
        LOGGER.debug("网络状态："+connection.getResponseCode()+" ");
        LOGGER.debug("inputStream状态："+(inputStream!=null)+" ");

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuffer sb = new StringBuffer("");
        int ss;
        while ((ss = reader.read()) != -1) {
            sb.append( (char)ss);
        }

        reader.close();
        return sb+"";
    }
}
